﻿namespace DreamBuilder.Common
{
    using DreamBuilder.Core.DAO;
    using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
    using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Web;

    public class DataAccessBase : IDataAccess
    {
        private const string DATETIMETYPE_KEY = "yyyy-MM-dd HH:mm:ss";
        private const string DATETYPE_KEY = "yyyy-MM-dd";
        private IDBHelper dbHelper;

        public bool CheckFieldValueExist(string sTableCode, string[] sFieldCode, object[] sData)
        {
            try
            {
                string strSql = "";
                for (int i = 0; i < sFieldCode.Length; i++)
                {
                    if ((sFieldCode[i] != null) && (sFieldCode[i].Trim() != ""))
                    {
                        if (sData[i] == DBNull.Value)
                        {
                            strSql = strSql + " " + sFieldCode[i] + "  is null and ";
                        }
                        else
                        {
                            strSql = strSql + " " + sFieldCode[i] + "  = '" + sData[i].ToString() + "' and ";
                        }
                    }
                }
                if (this.DBHelper.database is OracleDatabase)
                {
                    strSql = "select Count(1) from " + sTableCode + "  where " + strSql + "1=1";
                }
                else
                {
                    strSql = "select Count(1) from [" + sTableCode + "] where " + strSql + "1=1";
                }
                return (int.Parse(this.DBHelper.ExecuteDataSet(strSql).Tables[0].Rows[0][0].ToString()) > 0);
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool CheckFieldValueExistExceptTheValue(string sTableCode, string[] sFieldCode, object[] sData, string sPKField, string sPKValue)
        {
            try
            {
                string strSql = "";
                for (int i = 0; i < sFieldCode.Length; i++)
                {
                    if ((sFieldCode[i] != null) && (sFieldCode[i].Trim() != ""))
                    {
                        if (sData[i] != DBNull.Value)
                        {
                            strSql = strSql + sFieldCode[i] + " = '" + sData[i].ToString() + "' and ";
                        }
                        else
                        {
                            strSql = strSql + sFieldCode[i] + " is null and ";
                        }
                    }
                }
                strSql = "select Count(1) from " + sTableCode + " where " + strSql + " " + sPKField + "  <> '" + sPKValue + "'";
                return (int.Parse(this.DBHelper.ExecuteDataSet(strSql).Tables[0].Rows[0][0].ToString()) > 0);
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void DeleteData(List<IDeleteData> deleteList)
        {
            Action<IDeleteData> action = null;
            Action<IDeleteData> action2 = null;
            string sSaveSql = "";
            if (this.DBHelper.database is OracleDatabase)
            {
                sSaveSql = "begin ";
            }
            if (this.DBHelper.GetScopeTransaction() != null)
            {
                if (action == null)
                {
                    action = delegate (IDeleteData deleteData) {
                        string str = GenerateDeleteSql(deleteData.TableCode, deleteData.PTKName, deleteData.PTKValue);
                        if (!string.IsNullOrEmpty(str))
                        {
                            sSaveSql = sSaveSql + str + ";";
                        }
                    };
                }
                deleteList.ForEach<IDeleteData>(action);
                if (this.DBHelper.database is OracleDatabase)
                {
                    sSaveSql = sSaveSql + "end; ";
                }
                this.DBHelper.ExecuteSql(sSaveSql);
            }
            else
            {
                using (DbConnection connection = this.DBHelper.database.CreateConnection())
                {
                    connection.Open();
                    DbTransaction transaction = connection.BeginTransaction();
                    try
                    {
                        if (action2 == null)
                        {
                            action2 = delegate (IDeleteData deleteData) {
                                string str = GenerateDeleteSql(deleteData.TableCode, deleteData.PTKName, deleteData.PTKValue);
                                if (!string.IsNullOrEmpty(str))
                                {
                                    sSaveSql = sSaveSql + str + ";";
                                }
                            };
                        }
                        deleteList.ForEach<IDeleteData>(action2);
                        if (this.DBHelper.database is OracleDatabase)
                        {
                            sSaveSql = sSaveSql + "end; ";
                        }
                        this.DBHelper.ExecuteSql(sSaveSql, transaction);
                        transaction.Commit();
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        public void DeleteData(DataSet dsSave)
        {
            int num2;
            string str2;
            int count = dsSave.Tables.Count;
            string strSql = "";
            if (this.DBHelper.database is OracleDatabase)
            {
                strSql = "begin ";
            }
            if (this.DBHelper.GetScopeTransaction() != null)
            {
                for (num2 = count - 1; num2 > -1; num2--)
                {
                    foreach (DataRow row in dsSave.Tables[num2].Rows)
                    {
                        str2 = "";
                        if (Convert.ToInt32(row["RowStatus"].ToString().Trim()) == 3)
                        {
                            str2 = this.GenerateDeleteSql(row);
                        }
                        if (str2 != "")
                        {
                            strSql = strSql + str2 + ";";
                        }
                    }
                }
                if (this.DBHelper.database is OracleDatabase)
                {
                    strSql = strSql + "end; ";
                }
                this.DBHelper.ExecuteSql(strSql);
            }
            else
            {
                using (DbConnection connection = this.DBHelper.database.CreateConnection())
                {
                    connection.Open();
                    DbTransaction transaction = connection.BeginTransaction();
                    try
                    {
                        for (num2 = count - 1; num2 > -1; num2--)
                        {
                            foreach (DataRow row in dsSave.Tables[num2].Rows)
                            {
                                str2 = "";
                                if (Convert.ToInt32(row["RowStatus"].ToString().Trim()) == 3)
                                {
                                    str2 = this.GenerateDeleteSql(row);
                                }
                                if (str2 != "")
                                {
                                    strSql = strSql + str2 + ";";
                                }
                            }
                        }
                        if (this.DBHelper.database is OracleDatabase)
                        {
                            strSql = strSql + "end; ";
                        }
                        this.DBHelper.ExecuteSql(strSql, transaction);
                        transaction.Commit();
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        private string FormatDateType(string Date)
        {
            IFormatProvider provider;
            string str;
            DateTime time;
            string str3 = Thread.CurrentThread.CurrentCulture.Name.ToUpper();
            if (str3 != null)
            {
                if (!(str3 == "ZH-CN"))
                {
                    if (str3 == "EN-US")
                    {
                        provider = new CultureInfo("en-US");
                        goto Label_007B;
                    }
                    if (str3 == "RU-RU")
                    {
                        provider = new CultureInfo("ru-RU");
                        goto Label_007B;
                    }
                }
                else
                {
                    provider = new CultureInfo("zh-CN");
                    goto Label_007B;
                }
            }
            provider = new CultureInfo("ru-RU");
        Label_007B:
            time = DateTime.Parse(Date, provider);
            if (((time.Hour.ToString().Trim() == "0") && (time.Minute.ToString().Trim() == "00")) && (time.Second.ToString().Trim() == "00"))
            {
                str = time.ToString("yyyy-MM-dd");
            }
            else
            {
                str = time.ToString("yyyy-MM-dd HH:mm:ss");
            }
            if (this.DBHelper.database is OracleDatabase)
            {
                return ("to_date('" + time + "','yyyy-mm-dd hh24:mi:ss')");
            }
            return ("'" + time + "'");
        }

        private string FormatFieldDataForSql(object fieldValue, Type fieldType)
        {
            if (fieldValue == DBNull.Value)
            {
                return "null";
            }
            switch (fieldType.FullName)
            {
                case "System.Boolean":
                    return (Convert.ToBoolean(fieldValue) ? "1" : "0");

                case "System.String":
                    return ("N'" + CStringFormat.SqlStrFormat2(fieldValue.ToString()) + "'");

                case "System.DateTime":
                    return (this.FormatDateType(fieldValue.ToString()) ?? "");
            }
            return fieldValue.ToString();
        }

        private string GenerateDeleteSql(DataRow drInfo)
        {
            string tableName = drInfo.Table.TableName;
            string columnName = drInfo.Table.PrimaryKey[0].ColumnName;
            return ("delete " + tableName + " where " + columnName + " = '" + drInfo[columnName].ToString() + "'");
        }

        public static string GenerateDeleteSql(string tableCode, string pkName, string pkValue)
        {
            if (pkValue.IndexOf(",") > 0)
            {
                pkValue = pkValue.Replace(",", "','");
            }
            return ("delete from  " + tableCode + " where " + pkName + " in ('" + CStringFormat.SqlStrFormat(pkValue) + "')");
        }

        private string GenerateInsertSql(DataRow drInfo)
        {
            string tableName = drInfo.Table.TableName;
            string str2 = "insert into " + tableName + "(";
            string str3 = "values (";
            foreach (DataColumn column in drInfo.Table.Columns)
            {
                if ((column.ColumnName.ToLower() != "RowStatus".ToLower()) && (column.ColumnName.ToLower() != (tableName.ToLower() + ".ts")))
                {
                    str2 = str2 + " " + column.ColumnName + ",";
                    if (drInfo[column.ColumnName] == DBNull.Value)
                    {
                        str3 = str3 + "null,";
                    }
                    else
                    {
                        str3 = str3 + this.FormatFieldDataForSql(drInfo[column.ColumnName], column.DataType) + " ,";
                    }
                }
            }
            str2 = str2.TrimEnd(new char[] { ',' }) + ")";
            str3 = str3.TrimEnd(new char[] { ',' }) + ")";
            return (str2 + " " + str3);
        }

        private string GenerateModifySql(DataRow drInfo)
        {
            string tableName = drInfo.Table.TableName;
            string columnName = drInfo.Table.PrimaryKey[0].ColumnName;
            string str3 = "update " + tableName + " set ";
            foreach (DataColumn column in drInfo.Table.Columns)
            {
                if (((column.ColumnName.ToLower() != "RowStatus".ToLower()) && (column.ColumnName.ToLower() != (tableName.ToLower() + ".ts"))) && (column.ColumnName.ToLower() != columnName.ToLower()))
                {
                    if (drInfo[column.ColumnName] == DBNull.Value)
                    {
                        str3 = str3 + " " + column.ColumnName + " = null,";
                    }
                    else
                    {
                        str3 = str3 + column.ColumnName + " = " + this.FormatFieldDataForSql(drInfo[column.ColumnName], column.DataType) + " ,";
                    }
                }
            }
            if (str3.Length > 0)
            {
                str3 = str3.TrimEnd(new char[] { ',' }) + " where " + columnName + " = '" + drInfo[columnName].ToString() + "'";
            }
            return str3;
        }

        private DbType GetDBType(Type type)
        {
            DbType @decimal = DbType.String;
            if (((type == typeof(decimal)) || (type == typeof(double))) || (type == typeof(float)))
            {
                @decimal = DbType.Decimal;
            }
            if (type == typeof(string))
            {
                @decimal = DbType.String;
            }
            if (type == typeof(DateTime))
            {
                @decimal = DbType.DateTime;
            }
            return @decimal;
        }

        private DbCommand GetDeleteCommand(DataTable table, DataTableMapping tableMapping, string pk)
        {
            StringBuilder builder = new StringBuilder("DELETE ");
            builder.Append(tableMapping.SourceTable);
            builder.Append(" WHERE ");
            builder.Append(pk);
            builder.Append(" = ");
            builder.Append(this.DBHelper.BuildParameterName("PK_" + pk));
            builder.Append(" ");
            DbCommand sqlStringCommand = this.DBHelper.database.GetSqlStringCommand(builder.ToString());
            this.DBHelper.database.AddParameter(sqlStringCommand, "PK_" + pk, this.GetDBType(table.Columns[pk].DataType), ParameterDirection.Input, pk, DataRowVersion.Current, null);
            return sqlStringCommand;
        }

        public DataTable GetFKRefByOtherTables(string tableName)
        {
            string strSql = null;
            if (this.DBHelper.database is OracleDatabase)
            {
                strSql = "SELECT t2.table_name as UseRefTableName ,t2.column_name as UseRefColumnName\r\n                        FROM User_Constraints t\r\n                        left outer join User_Constraints t1 on t1.constraint_type = 'p'\r\n                                     and t1.index_name = t.constraint_name\r\n                                     and t1.table_name = '" + tableName.ToUpper() + "'\r\n                        left outer join user_cons_columns t2 on t2.table_name = t.table_name \r\n                                    and t2.constraint_name =  t.constraint_name\r\n                        WHERE t.constraint_type = 'R' ";
            }
            else
            {
                strSql = "SELECT   UseRefTableName = object_name(b.fkeyid)\r\n\t                        ,UseRefColumnName =(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid)\r\n                        FROM sysobjects a\r\n\t                        join sysforeignkeys b on a.id=b.constid\r\n\t                        join sysobjects c on a.parent_obj=c.id\r\n                        where a.xtype='f' AND c.xtype='U'\r\n\t                        and object_name(b.rkeyid)= ";
                strSql = strSql + "'" + tableName.ToUpper() + "'";
            }
            DataSet set = this.DBHelper.ExecuteDataSet(strSql);
            if ((set != null) && (set.Tables.Count > 0))
            {
                return set.Tables[0];
            }
            return null;
        }

        private DbCommand GetInserCommand(DataTable table, DataTableMapping tableMapping, string pk)
        {
            StringBuilder builder = new StringBuilder("INSERT INTO ");
            builder.Append(tableMapping.SourceTable);
            builder.Append(" (");
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                if ((!(this.DBHelper.database is SqlDatabase) || !string.Equals(mapping.SourceColumn, pk, StringComparison.CurrentCultureIgnoreCase)) || !table.Columns[pk].AutoIncrement)
                {
                    builder.Append(mapping.SourceColumn);
                    builder.Append(",");
                }
            }
            builder.Remove(builder.Length - 1, 1);
            builder.Append(") VALUES (");
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                if ((!(this.DBHelper.database is SqlDatabase) || !string.Equals(mapping.SourceColumn, pk, StringComparison.CurrentCultureIgnoreCase)) || !table.Columns[pk].AutoIncrement)
                {
                    builder.Append(this.DBHelper.BuildParameterName(mapping.SourceColumn) + ",");
                }
            }
            builder.Remove(builder.Length - 1, 1);
            builder.Append(") ");
            if ((this.DBHelper.database is SqlDatabase) && table.Columns[pk].AutoIncrement)
            {
                builder.Append(";SELECT scope_identity() AS " + pk);
            }
            DbCommand sqlStringCommand = this.DBHelper.database.GetSqlStringCommand(builder.ToString());
            if ((this.DBHelper.database is SqlDatabase) && table.Columns[pk].AutoIncrement)
            {
                sqlStringCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
            }
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                if ((!(this.DBHelper.database is SqlDatabase) || !string.Equals(mapping.SourceColumn, pk, StringComparison.CurrentCultureIgnoreCase)) || !table.Columns[pk].AutoIncrement)
                {
                    this.DBHelper.database.AddParameter(sqlStringCommand, mapping.SourceColumn, this.GetDBType(table.Columns[mapping.DataSetColumn].DataType), ParameterDirection.Input, mapping.DataSetColumn, DataRowVersion.Current, null);
                }
            }
            return sqlStringCommand;
        }

        public DataTable GetRestrictFKSInfo(string tableName)
        {
            string strSql = null;
            if (this.DBHelper.database is OracleDatabase)
            {
                strSql = "select distinct (col.column_name) as OwnKeyName ,\r\n                r.table_name as RefKeyTableName,\r\n                r.column_name  as  RefKeyColumnName       \r\n                　　from\r\n                　　user_constraints con,\r\n                　　user_cons_columns col,\r\n                　　 (select t2.table_name,\r\n                             t2.column_name,\r\n                             t1.r_constraint_name\r\n                             　　from user_constraints t1,\r\n                             user_cons_columns t2                 \r\n                             　　where t1.r_constraint_name = t2.constraint_name\r\n                             　　and t1.table_name ='" + tableName + "'                    \r\n                             　　) r\r\n                　　where con.constraint_name = col.constraint_name\r\n                　　and con.r_constraint_name = r.r_constraint_name\r\n                　　and con.table_name = ";
            }
            else
            {
                strSql = "SELECT \r\n\t                             OwnKeyName=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid)\r\n\t                            ,RefKeyTableName = object_name(b.rkeyid)\r\n\t                            ,RefKeyColumnName=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid)\r\n                            FROM sysobjects a\r\n\t                            join sysforeignkeys b on a.id=b.constid\r\n\t                            join sysobjects c on a.parent_obj=c.id\r\n                            where a.xtype='f' AND c.xtype='U' and object_name(b.fkeyid) = ";
            }
            strSql = strSql + "'" + tableName.ToUpper() + "'";
            DataSet set = this.DBHelper.ExecuteDataSet(strSql);
            if ((set != null) && (set.Tables.Count > 0))
            {
                return set.Tables[0];
            }
            return null;
        }

        public DataTable GetRestrictUQInfoByTable(string tableName)
        {
            string strSql = null;
            if (this.DBHelper.database is OracleDatabase)
            {
                strSql = " select col.column_name as ColName ,col.table_name as tbname, con.constraint_name as UniqueName\r\n                         from user_constraints con, user_cons_columns col\r\n                         where con.constraint_name = col.constraint_name\r\n                         and con.constraint_type = 'U'\r\n                         and col.table_name =";
            }
            else
            {
                strSql = "   SELECT ColName = C.name,tbname = O.Name, UniqueName = OU.name\r\n                              FROM sysindexes IX, sysindexkeys IXK, syscolumns C, sysobjects OU, sysobjects O   \r\n                              WHERE   IX.indid   NOT   IN(0,   255)   \r\n                              AND   IX.id   =   IXK.id   \r\n                              AND   IX.indid   =   IXK.indid   \r\n                              AND   IX.id   =   c.id   \r\n                              AND   IXK.colid   =   C.colid   \r\n                              AND   OU.parent_obj   =   IX.id   \r\n                              AND   OU.xtype   =   'UQ'   \r\n                              AND   OU.name   =   IX.name   \r\n                              AND   O.xtype   =   'U'   \r\n                              AND   O.id   =   IX.id   \r\n                              AND   O.Name =";
            }
            strSql = strSql + "'" + tableName.ToUpper() + "'";
            DataSet set = this.DBHelper.ExecuteDataSet(strSql);
            if ((set != null) && (set.Tables.Count > 0))
            {
                return set.Tables[0];
            }
            return null;
        }

        private DbCommand GetSelectCommand(DataTable table, DataTableMapping tableMapping)
        {
            StringBuilder builder = new StringBuilder("SELECT ");
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                builder.Append(mapping.SourceColumn);
                builder.Append(",");
            }
            builder.Remove(builder.Length - 1, 1);
            builder.Append(" FROM ");
            builder.Append(tableMapping.SourceTable);
            return this.DBHelper.database.GetSqlStringCommand(builder.ToString());
        }

        private DbCommand GetUpdateCommand(DataTable table, DataTableMapping tableMapping, string pk)
        {
            StringBuilder builder = new StringBuilder("UPDATE ");
            builder.Append(tableMapping.SourceTable);
            builder.Append(" SET ");
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                if (!string.Equals(mapping.SourceColumn, pk, StringComparison.CurrentCultureIgnoreCase))
                {
                    builder.Append(mapping.SourceColumn);
                    builder.Append(" = ");
                    builder.Append(this.DBHelper.BuildParameterName(mapping.SourceColumn));
                    builder.Append(",");
                }
            }
            builder.Remove(builder.Length - 1, 1);
            builder.Append(" WHERE ");
            builder.Append(pk);
            builder.Append(" = ");
            builder.Append(this.DBHelper.BuildParameterName("PK_"+pk));
            builder.Append(" ");
            DbCommand sqlStringCommand = this.DBHelper.database.GetSqlStringCommand(builder.ToString());
            foreach (DataColumnMapping mapping in tableMapping.ColumnMappings)
            {
                if (!string.Equals(mapping.SourceColumn, pk, StringComparison.CurrentCultureIgnoreCase))
                {
                    this.DBHelper.database.AddParameter(sqlStringCommand, mapping.SourceColumn, this.GetDBType(table.Columns[mapping.DataSetColumn].DataType), ParameterDirection.Input, mapping.DataSetColumn, DataRowVersion.Current, null);
                }
            }
            this.DBHelper.database.AddParameter(sqlStringCommand, "PK_" + pk, this.GetDBType(table.Columns[pk].DataType), ParameterDirection.Input, pk, DataRowVersion.Current, null);
            return sqlStringCommand;
        }

        public void SaveData(DataSet dsSave)
        {
            int num2;
            string str2;
            string str3;
            int count = dsSave.Tables.Count;
            string str = string.Empty;
            if (this.DBHelper.database is OracleDatabase)
            {
                str = "begin ";
            }
            DbTransaction scopeTransaction = this.DBHelper.GetScopeTransaction();
            if (scopeTransaction != null)
            {
                for (num2 = 0; num2 < count; num2++)
                {
                    foreach (DataRow row in dsSave.Tables[num2].Rows)
                    {
                        str2 = "";
                        switch (Convert.ToInt32(row["RowStatus"].ToString().Trim()))
                        {
                            case 1:
                                str2 = this.GenerateInsertSql(row);
                                break;

                            case 2:
                                str2 = this.GenerateModifySql(row);
                                break;
                        }
                        if (!string.IsNullOrEmpty(str2))
                        {
                            this.DBHelper.ExecuteSql(str2, scopeTransaction);
                        }
                    }
                }
                for (num2 = count - 1; num2 > -1; num2--)
                {
                    foreach (DataRow row in dsSave.Tables[num2].Rows)
                    {
                        str3 = "";
                        if (row.RowState == DataRowState.Deleted)
                        {
                            row.RejectChanges();
                        }
                        if (Convert.ToInt32(row["RowStatus"].ToString().Trim()) == 3)
                        {
                            str3 = this.GenerateDeleteSql(row);
                        }
                        if (!string.IsNullOrEmpty(str3))
                        {
                            this.DBHelper.ExecuteSql(str3, scopeTransaction);
                        }
                    }
                }
            }
            else
            {
                using (DbConnection connection = this.DBHelper.database.CreateConnection())
                {
                    connection.Open();
                    scopeTransaction = connection.BeginTransaction();
                    try
                    {
                        for (num2 = 0; num2 < count; num2++)
                        {
                            foreach (DataRow row in dsSave.Tables[num2].Rows)
                            {
                                if (row.RowState == DataRowState.Deleted)
                                {
                                    continue;
                                }
                                str2 = "";
                                switch (Convert.ToInt32(row["RowStatus"].ToString().Trim()))
                                {
                                    case 1:
                                        str2 = this.GenerateInsertSql(row);
                                        break;

                                    case 2:
                                        str2 = this.GenerateModifySql(row);
                                        break;
                                }
                                if (!string.IsNullOrEmpty(str2))
                                {
                                    str = str + str2 + ";";
                                }
                            }
                        }
                        for (num2 = count - 1; num2 > -1; num2--)
                        {
                            foreach (DataRow row in dsSave.Tables[num2].Rows)
                            {
                                str3 = "";
                                if (row.RowState == DataRowState.Deleted)
                                {
                                    row.RejectChanges();
                                }
                                if (Convert.ToInt32(row["RowStatus"].ToString().Trim()) == 3)
                                {
                                    str3 = this.GenerateDeleteSql(row);
                                }
                                if (!string.IsNullOrEmpty(str3))
                                {
                                    str = str + str3 + ";";
                                }
                            }
                        }
                        if (this.DBHelper.database is OracleDatabase)
                        {
                            str = str + "end; ";
                        }
                        if (!string.IsNullOrEmpty(str))
                        {
                            this.DBHelper.ExecuteSql(str, scopeTransaction);
                        }
                        scopeTransaction.Commit();
                    }
                    catch
                    {
                        scopeTransaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        public void SaveData(out DataSet dsOut, DataSet dsSave, string[] tables, string[] primaryKeys, IKeyGen[] keyGens)
        {
            dsOut = new DataSet();
            DataTableMappingCollection tableMappings = new DataTableMappingCollection();
            foreach (string str in tables)
            {
                DataTable table = dsSave.Tables[str];
                if (table == null)
                {
                    return;
                }
                DataTableMapping mapping = new DataTableMapping(str, str);
                foreach (DataColumn column in table.Columns)
                {
                    mapping.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }
                tableMappings.Add(mapping);
            }
            this.SaveData(dsOut, dsSave, tableMappings, primaryKeys, keyGens);
        }

        public void SaveData(DataSet dsOut, DataSet dsSave, DataTableMappingCollection tableMappings, string[] primaryKeys, IKeyGen[] keyGens)
        {
            DataTable table;
            int num2;
            int count = tableMappings.Count;
            DataSet changes = dsSave.GetChanges(DataRowState.Added);
            DataSet set2 = dsSave.GetChanges(DataRowState.Modified);
            DataSet set3 = dsSave.GetChanges(DataRowState.Deleted);
            DbTransaction scopeTransaction = this.DBHelper.GetScopeTransaction();
            if (scopeTransaction != null)
            {
                for (num2 = 0; num2 < count; num2++)
                {
                    if ((changes != null) && changes.Tables.Contains(tableMappings[num2].DataSetTable))
                    {
                        table = changes.Tables[tableMappings[num2].DataSetTable];
                        if ((table != null) && (table.Rows.Count > 0))
                        {
                            this.SaveData(changes, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Insert);
                        }
                    }
                    if ((set2 != null) && set2.Tables.Contains(tableMappings[num2].DataSetTable))
                    {
                        table = set2.Tables[tableMappings[num2].DataSetTable];
                        if ((table != null) && (table.Rows.Count > 0))
                        {
                            this.SaveData(set2, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Update);
                        }
                    }
                }
                for (num2 = count - 1; num2 > -1; num2--)
                {
                    if ((set3 != null) && set3.Tables.Contains(tableMappings[num2].DataSetTable))
                    {
                        table = set3.Tables[tableMappings[num2].DataSetTable];
                        if ((table != null) && (table.Rows.Count > 0))
                        {
                            this.SaveData(set3, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Delete);
                        }
                    }
                }
            }
            else
            {
                using (DbConnection connection = this.DBHelper.database.CreateConnection())
                {
                    connection.Open();
                    scopeTransaction = connection.BeginTransaction();
                    try
                    {
                        for (num2 = 0; num2 < count; num2++)
                        {
                            if ((changes != null) && changes.Tables.Contains(tableMappings[num2].DataSetTable))
                            {
                                table = changes.Tables[tableMappings[num2].DataSetTable];
                                if ((table != null) && (table.Rows.Count > 0))
                                {
                                    this.SaveData(changes, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Insert);
                                }
                            }
                            if ((set2 != null) && set2.Tables.Contains(tableMappings[num2].DataSetTable))
                            {
                                table = set2.Tables[tableMappings[num2].DataSetTable];
                                if ((table != null) && (table.Rows.Count > 0))
                                {
                                    this.SaveData(set2, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Update);
                                }
                            }
                        }
                        for (num2 = count - 1; num2 > -1; num2--)
                        {
                            if ((set3 != null) && set3.Tables.Contains(tableMappings[num2].DataSetTable))
                            {
                                table = set3.Tables[tableMappings[num2].DataSetTable];
                                if ((table != null) && (table.Rows.Count > 0))
                                {
                                    this.SaveData(set3, table, tableMappings[num2], primaryKeys[num2], keyGens[num2], scopeTransaction, SaveStatus.Delete);
                                }
                            }
                        }
                        scopeTransaction.Commit();
                    }
                    catch
                    {
                        scopeTransaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            DataSet dataSet = dsSave.Copy();
            List<DataRow> list = new List<DataRow>();
            foreach (DataTable table2 in dataSet.Tables)
            {
                foreach (DataRow row in table2.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                        list.Add(row);
                    }
                }
            }
            foreach (DataRow row in list)
            {
                row.Delete();
            }
            dataSet.AcceptChanges();
            dsOut.Merge(dataSet);
            if (changes != null)
            {
                dsOut.Merge(changes);
            }
            dsOut.AcceptChanges();
        }

        public void SaveData(DataSet dsSave, DataTable table, DataTableMapping tableMapping, string pk, IKeyGen keyGen, DbTransaction transaction, SaveStatus saveStatus)
        {
            DbCommand insertCommand = null;
            DbCommand updateCommand = null;
            DbCommand deleteCommand = null;
            if (saveStatus == SaveStatus.All)
            {
                insertCommand = this.GetInserCommand(table, tableMapping, pk);
                updateCommand = this.GetUpdateCommand(table, tableMapping, pk);
                deleteCommand = this.GetDeleteCommand(table, tableMapping, pk);
            }
            else if (saveStatus == SaveStatus.Insert)
            {
                insertCommand = this.GetInserCommand(table, tableMapping, pk);
            }
            else if (saveStatus == SaveStatus.Update)
            {
                updateCommand = this.GetUpdateCommand(table, tableMapping, pk);
            }
            else if (saveStatus == SaveStatus.Delete)
            {
                deleteCommand = this.GetDeleteCommand(table, tableMapping, pk);
            }
            if ((keyGen != null) && (keyGen is SequenceKeyGen))
            {
                foreach (DataRow row in table.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                        row[tableMapping.ColumnMappings.IndexOfDataSetColumn(pk)] = keyGen.GenKey();
                    }
                }
            }
            this.DBHelper.database.UpdateDataSet(dsSave, table.TableName, insertCommand, updateCommand, deleteCommand, transaction);
        }

        public IDBHelper DBHelper
        {
            get
            {
                if (this.dbHelper == null)
                {
                    EPPage handler = HttpContext.Current.Handler as EPPage;
                    if (!((handler == null) || string.IsNullOrEmpty(handler.DBHelpName)))
                    {
                        this.dbHelper = DBHelperFactory.CreateInstance(handler.DBHelpName);
                    }
                }
                return this.dbHelper;
            }
            set
            {
                this.dbHelper = value;
            }
        }
    }
}

